package com.tangdi.production.mpaychl.controller.third;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.tangdi.production.mpaychl.controller.BaseController;
import com.tangdi.production.mpaychl.service.impl.ksunpay.KsunpayServiceImpl;
import com.tangdi.production.mpaychl.service.impl.ksunpay.util.MD5;
import com.tangdi.production.mpbase.constants.ExcepCode;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.BusinessException;
import com.tangdi.production.mpbase.service.OrderService;
import com.tangdi.production.mpbase.util.MoneyUtils;

@Controller
@RequestMapping("sunpay")
public class KsunpayController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(KsunpayController.class);
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value={"/notify-url"},method={RequestMethod.POST})
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response){
		logger.info("sunpay异步回调开始");
		
        // 将异步通知中收到的所有参数都存放到map中
        Map<String, String> paramsMap = getRequestParams(request);
        logger.info("异步回调,获取sunpay异步返回,参数:{}", paramsMap);
        
        try {
            // 签名
            String memberid=request.getParameter("memberid");
            String orderid=request.getParameter("orderid");
            String amount=request.getParameter("amount");
            String datetime=request.getParameter("datetime");
            String returncode=request.getParameter("returncode");
            String transaction_id = request.getParameter("transaction_id");
            String attach=request.getParameter("attach");
            String sign=request.getParameter("sign");
            String keyValue=KsunpayServiceImpl.key_Value;
            String SignTemp="amount="+amount+"&datetime="+datetime+"&memberid="+memberid+"&orderid="+orderid+"&returncode="+returncode+"&transaction_id="+transaction_id+"&key="+keyValue+"";
            String md5sign = MD5.md5(SignTemp);//MD5加密
            if (sign.equals(md5sign)){
                if(returncode.equals("00")){
                    //支付成功，写返回数据逻辑
                    respContent(response, "ok");
                }else{
                    logger.error("支付失败");
                    returnFailure(response);
                    return;
                }
            }else{
                logger.error("验签失败");
                returnFailure(response);
                return;
            }
            
			// 订单号
			String prdOrdNo = orderid;
			if(StringUtils.isEmpty(prdOrdNo)){
				throw new BusinessException(ExcepCode.EX900000,"回调订单号为空");
			}
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("prdOrdNo", prdOrdNo);
			Map<String,Object> prdOrdMap = orderService.getPrdOrdMap(queryMap);
			
			String ordStatus = (String) prdOrdMap.get("ordStatus");
			if(MsgCT.ORDSTATUS_SUCCESS.equals(ordStatus)){//成功的订单不允许再更新
				logger.warn("订单状态已成功，不允许更新...");
				returnSuccess(response);
				return;
			}
			
			logger.info("支付订单金额[{}]元", amount);
			amount = MoneyUtils.toStrCent(amount);
			if(amount.equals(prdOrdMap.get("txAmt").toString()) == false){
				throw new BusinessException(ExcepCode.EX900000,"支付金额不一致 成功金额[{}] 订单支付金额[{}]",amount, prdOrdMap.get("txAmt").toString());
			}
			
			//原交易大商户编号
			String mchNo = (String)prdOrdMap.get("TMERCID");
			if(StringUtils.isEmpty(mchNo)){
				throw new BusinessException(ExcepCode.EX900000,"原交易商户号不能为空");
			}
			
			//定义回调订单信息Map
			Map<String,Object> orderCallBackMap = new HashMap<String, Object>();
			orderCallBackMap.put("prdOrdNo", prdOrdMap.get("prdOrdNo"));//订单号
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
			orderCallBackMap.put("resJson", JSON.toJSONString(paramsMap));
			
			//支付成功
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_SUCCESS);
			
			//调用回调更新订单
			logger.info("通知平台更新订单[{}]",orderCallBackMap);
			orderService.prdPayCallBack(orderCallBackMap);
			
            // 处理成功后，需要返回SUCCESS，通知中心接受到SUCCESS后将不再通知
            returnSuccess(response);
        	
        } catch (Exception e){
        	logger.error("sunpay异步通知失败:{}", e.getMessage(), e);
        }

		logger.info("sunpay异步回调完成");
	}
	
    /**
     * 从请求中获取所有的请求参数
     * 
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    protected Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new TreeMap<String, String>();
        Enumeration<String> names = request.getParameterNames();
        
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            
            params.put(name, value);
        }
        
        return params;
    }
}
